﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using HYStandardRoom;
using LevelDatabase;
using Transfer.Properties;
using Transfer.Utils;

namespace Transfer.CrossDocument
{
	public partial class CrossDocCopyForm : System.Windows.Forms.Form
	{
		public CrossDocCopyForm(UIApplication uiApplication, ElementSelector elementSelector)
		{
			this.InitializeComponent();
			this.m_UIApplication = uiApplication;
			this.m_ElementSelector = elementSelector;
			this.btnSetAngle.Visible = false;
		}

		public bool SettingAngle
		{
			get
			{
				return this.m_SettingAngle;
			}
		}

		public double Angle
		{
			get
			{
				return (double)Convert.ToInt32(this.txbAngle.Text) * 1.0 / 180.0 * Math.PI;
			}
			set
			{
				double num = value * 180.0 / Math.PI;
				this.txbAngle.Text = num.ToString("f0");
			}
		}

		public bool Mirror
		{
			get
			{
				return this.chkMirror.Checked;
			}
		}

		public string GetSourceFileName()
		{
			if (this.rbDbDocList.Checked)
			{
				int index = this.FindSelectedStdRoomIndex();
				return this.m_DatebaseDocumentFillNameList[index];
			}
			return this.m_GeneralDocumentFillNameList[this.cmbDocuments.SelectedIndex];
		}

		private void UpdateCheckedTypeList(Autodesk.Revit.DB.Document doc)
		{
			this.chblFilter.Focus();
			this.chblFilter.Items.Clear();
			if (doc == null)
			{
				return;
			}
			List<string> allTypeNames = this.m_ElementSelector.GetAllTypeNames(doc);
			for (int i = 0; i < allTypeNames.Count; i++)
			{
				string item = allTypeNames[i];
				this.chblFilter.Items.Add(item);
				this.chblFilter.SetItemChecked(i, true);
			}
		}

		private void cmbDocuments_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (this.cmbDocuments.SelectedIndex == this.cmbDocuments.Items.Count - 1)
			{
				OpenFileDialog dlg = new OpenFileDialog();
				dlg.DefaultExt = "rvt";
				dlg.Filter = "Revit project files (*.rvt)|*.rvt|Revit family files (*.rfa)|*.rfa|Revit family template files (*.rft)|*.rft";
				if (dlg.ShowDialog() != DialogResult.OK)
				{
					this.cmbDocuments.SelectedIndex = -1;
					return;
				}
				if (dlg.FileName.CompareTo(this.m_UIApplication.ActiveUIDocument.Document.PathName) == 0)
				{
					YJKMessageBox.Show("当前文档已经打开");
					return;
				}
				if (this.m_GeneralDocumentFillNameList.FindIndex((string s) => s.CompareTo(dlg.FileName) == 0) != -1)
				{
					YJKMessageBox.Show("当前文档已经在文档列表中");
					return;
				}
				Document document = null;
				try
				{
					document = this.m_UIApplication.Application.OpenDocumentFile(dlg.FileName);
				}
				catch (Exception)
				{
					YJKMessageBox.Show("文档打开出错");
					return;
				}
				if (document != null)
				{
					this.m_GeneralDocumentFillNameList.Insert(0, document.PathName);
					this.m_GeneralDocumentList.Insert(0, document);
					this.cmbDocuments.Items.Insert(0, document.PathName);
					this.cmbDocuments.SelectedIndex = 0;
					return;
				}
			}
			else
			{
				Document currentDocument = this.GetCurrentDocument();
				if (currentDocument == null)
				{
					return;
				}
				this.Update3DView(currentDocument);
				this.UpdateCheckedTypeList(currentDocument);
			}
		}

		private Document GetCurrentDocument()
		{
			Document document = null;
			if (this.rbDbDocList.Checked)
			{
				int num = this.FindSelectedStdRoomIndex();
				if (-1 == num)
				{
					return null;
				}
				document = this.m_DatebaseDocumentList[num];
				if (document == null)
				{
					try
					{
						document = this.m_DBStdRoomList[num].Open(this.m_UIApplication.Application);
						this.m_DatebaseDocumentList[num] = document;
						this.m_DatebaseDocumentFillNameList[num] = document.PathName;
					}
					catch (Exception)
					{
						return null;
					}
				}
				return document;
			}
			else
			{
				if (this.cmbDocuments.SelectedIndex == -1)
				{
					return null;
				}
				document = this.m_GeneralDocumentList[this.cmbDocuments.SelectedIndex];
				if (document == null)
				{
					try
					{
						document = this.m_UIApplication.Application.OpenDocumentFile(this.m_GeneralDocumentFillNameList[this.cmbDocuments.SelectedIndex]);
						this.m_GeneralDocumentList[this.cmbDocuments.SelectedIndex] = document;
					}
					catch (Exception)
					{
						return null;
					}
				}
				return document;
			}
			Document result;
			return result;
		}

		private void InitializeDatebaseDocuments(bool setItem)
		{
			try
			{
				this.m_DatebaseDocumentList.Clear();
				this.m_DatebaseDocumentFillNameList.Clear();
				this.m_DBStdRoomList.Clear();
				this.m_LeafTreeNodeIndex.Clear();
				string versionNumber = this.m_UIApplication.Application.VersionNumber;
				TreeView tree = StandardRoomCategory.GetTree(RelationDatabase.GetSqliteDB("StandardRoom" + versionNumber + ".db", versionNumber));
				this.tvStdRoomFileList.Nodes.Clear();
				foreach (object obj in tree.Nodes)
				{
					TreeNode treeNode = ((TreeNode)obj).Clone() as TreeNode;
					this.GetLeafNodeInfo(treeNode);
					this.tvStdRoomFileList.Nodes.Add(treeNode);
				}
				this.tvStdRoomFileList.ExpandAll();
				if (this.tvStdRoomFileList.GetNodeCount(true) > 0)
				{
					TreeNode treeNode2 = null;
					this.GetFirstLeafNode(this.tvStdRoomFileList.Nodes[0], ref treeNode2);
					if (treeNode2 != null)
					{
						this.tvStdRoomFileList.SelectedNode = treeNode2;
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private void InitializeGeneralDocuments(bool setItem)
		{
			this.cmbDocuments.Items.Clear();
			this.m_GeneralDocumentList.Clear();
			foreach (string item in this.m_GeneralDocumentFillNameList)
			{
				Document item2 = null;
				this.m_GeneralDocumentList.Add(item2);
				this.cmbDocuments.Items.Add(item);
			}
			this.cmbDocuments.Items.Add("<Open Document...>");
			if (setItem && this.cmbDocuments.Items.Count > 1)
			{
				this.cmbDocuments.SelectedIndex = 0;
			}
		}

		private void CloseDocuments()
		{
			foreach (Autodesk.Revit.DB.Document document in this.m_GeneralDocumentList)
			{
				try
				{
					document.Close(false);
				}
				catch (Exception)
				{
				}
			}
			foreach (Autodesk.Revit.DB.Document document2 in this.m_DatebaseDocumentList)
			{
				try
				{
					document2.Close(false);
				}
				catch (Exception)
				{
				}
			}
		}

		private void Update3DView(Autodesk.Revit.DB.Document doc)
		{
			PreviewControl previewControl = this.elementHost.Child as PreviewControl;
			if (doc == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.View));
			IEnumerable<Autodesk.Revit.DB.View> enumerable = from Element f in filteredElementCollector
			where (f as Autodesk.Revit.DB.View).CanBePrinted
			select f as Autodesk.Revit.DB.View;
			Autodesk.Revit.DB.View view = null;
			foreach (Autodesk.Revit.DB.View view2 in enumerable)
			{
				if ((int)view2.ViewType == 4)
				{
					view = view2;
					break;
				}
			}
			if (view == null)
			{
				foreach (Autodesk.Revit.DB.View view3 in enumerable)
				{
					if ((int)view3.ViewType == 1)
					{
						view = view3;
						break;
					}
				}
			}
			if (view == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
			if (previewControl != null)
			{
				previewControl.Dispose();
			}
			try
			{
				this.elementHost.Child = new PreviewControl(doc, view.Id);
			}
			catch (ArgumentException ex)
			{
				ex.ToString();
				MessageBox.Show("无法打开此模型，此模型已链接至一个或多个已打开的文档。");
			}
		}

		public void SaveData()
		{
			FileStream fileStream = new FileStream(Path.GetTempPath() + "CrossDocCopyForm.dat", FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(this.rbDbDocList.Checked);
			streamWriter.WriteLine(this.m_GeneralDocumentFillNameList.Count);
			foreach (string value in this.m_GeneralDocumentFillNameList)
			{
				streamWriter.WriteLine(value);
			}
			streamWriter.WriteLine(this.cmbDocuments.SelectedIndex);
			streamWriter.WriteLine(this.txbAngle.Text);
			streamWriter.WriteLine(this.chkMirror.Checked);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private void ReadData()
		{
			this.m_GeneralDocumentList.Clear();
			this.m_GeneralDocumentFillNameList.Clear();
			this.m_DatebaseDocumentList.Clear();
			this.m_DatebaseDocumentFillNameList.Clear();
			this.m_DBStdRoomList.Clear();
			this.m_LeafTreeNodeIndex.Clear();
			this.cmbDocuments.Items.Clear();
			string path = Path.GetTempPath() + "CrossDocCopyForm.dat";
			if (!File.Exists(path))
			{
				this.SetSelectDocumentState(true);
				this.InitializeDatebaseDocuments(true);
				this.InitializeGeneralDocuments(false);
				return;
			}
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			bool selectDocumentState = Convert.ToBoolean(streamReader.ReadLine());
			this.SetSelectDocumentState(selectDocumentState);
			this.InitializeDatebaseDocuments(this.rbDbDocList.Checked);
			this.m_GeneralDocumentFillNameList.Clear();
			int num = Convert.ToInt32(streamReader.ReadLine());
			for (int i = 0; i < num; i++)
			{
				string text = streamReader.ReadLine();
				if (File.Exists(text))
				{
					this.m_GeneralDocumentFillNameList.Add(text);
				}
			}
			this.InitializeGeneralDocuments(this.rbGeneralDocList.Checked);
			int num2 = Convert.ToInt32(streamReader.ReadLine());
			if (!this.rbDbDocList.Checked)
			{
				if (num2 < this.cmbDocuments.Items.Count)
				{
					this.cmbDocuments.SelectedIndex = num2;
				}
				else if (this.cmbDocuments.Items.Count > 1)
				{
					this.cmbDocuments.SelectedIndex = 0;
				}
			}
			this.txbAngle.Text = streamReader.ReadLine();
			this.chkMirror.Checked = Convert.ToBoolean(streamReader.ReadLine());
			streamReader.Close();
			fileStream.Close();
		}

		private void ImportGroupForm_Load(object sender, EventArgs e)
		{
			this.ReadData();
			new ToolTip
			{
				InitialDelay = 500,
				AutoPopDelay = 3000,
				ReshowDelay = 50,
				ShowAlways = true
			}.SetToolTip(this.btnClearGeneralDocList, "清空普通文件目录");
		}

		private void ImportGroupForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (base.DialogResult == DialogResult.Cancel)
			{
				this.CloseDocuments();
				this.SaveData();
				return;
			}
			if (this.rbDbDocList.Checked && this.FindSelectedStdRoomIndex() == -1)
			{
				YJKMessageBox.Show("未指定源文档");
				e.Cancel = true;
				return;
			}
			if (!this.rbDbDocList.Checked && this.cmbDocuments.Items.Count == 1)
			{
				YJKMessageBox.Show("未指定源文档");
				e.Cancel = true;
				return;
			}
			this.m_ElementSelector.CheckedCategoryNames = this.CheckedTypeList();
			this.SaveData();
			this.CloseDocuments();
		}

		private List<string> CheckedTypeList()
		{
			List<string> list = new List<string>();
			for (int i = 0; i < this.chblFilter.Items.Count; i++)
			{
				if (this.chblFilter.GetItemChecked(i))
				{
					list.Add(this.chblFilter.GetItemText(this.chblFilter.Items[i]));
				}
			}
			return list;
		}

		private void btnSetAngle_Click(object sender, EventArgs e)
		{
			this.m_SettingAngle = true;
		}

		private void btnOk_Click(object sender, EventArgs e)
		{
			this.m_SettingAngle = false;
		}

		private void txbAngle_Validating(object sender, CancelEventArgs e)
		{
			try
			{
				if (Geometry.GreaterThan((double)Math.Abs(int.Parse(this.txbAngle.Text)), 360.0))
				{
					YJKMessageBox.Show("角度范围无效，应该在：-360～360之间");
					e.Cancel = true;
				}
			}
			catch (FormatException)
			{
				YJKMessageBox.Show("角度范围无效，应该在：-360～360之间");
				e.Cancel = true;
			}
		}

		private void rbDbDocList_CheckedChanged(object sender, EventArgs e)
		{
			if (this.rbDbDocList.Checked)
			{
				this.cmbDocuments.Enabled = false;
				this.tvStdRoomFileList.Enabled = true;
				if (this.tvStdRoomFileList.GetNodeCount(true) > 0)
				{
					TreeNode treeNode = null;
					this.GetFirstLeafNode(this.tvStdRoomFileList.Nodes[0], ref treeNode);
					if (treeNode != null)
					{
						this.tvStdRoomFileList.SelectedNode = treeNode;
					}
				}
				Document currentDocument = this.GetCurrentDocument();
				this.Update3DView(currentDocument);
				this.UpdateCheckedTypeList(currentDocument);
				return;
			}
			this.tvStdRoomFileList.Enabled = false;
			this.cmbDocuments.Enabled = true;
			if (this.cmbDocuments.SelectedIndex == 0)
			{
				Document currentDocument2 = this.GetCurrentDocument();
				this.Update3DView(currentDocument2);
				this.UpdateCheckedTypeList(currentDocument2);
				return;
			}
			if (this.cmbDocuments.Items.Count > 1)
			{
				this.cmbDocuments.SelectedIndex = 0;
			}
		}

		private void SetSelectDocumentState(bool isDatebase)
		{
			if (isDatebase)
			{
				this.rbDbDocList.Checked = true;
				this.rbGeneralDocList.Checked = false;
				this.cmbDocuments.Enabled = false;
				this.tvStdRoomFileList.Enabled = true;
				return;
			}
			this.rbGeneralDocList.Checked = true;
			this.rbDbDocList.Checked = false;
			this.tvStdRoomFileList.Enabled = false;
			this.cmbDocuments.Enabled = true;
		}

		private void tvStdRoomFileList_AfterSelect(object sender, TreeViewEventArgs e)
		{
			Document currentDocument = this.GetCurrentDocument();
			this.Update3DView(currentDocument);
			this.UpdateCheckedTypeList(currentDocument);
		}

		private void btnSelAll_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < this.chblFilter.Items.Count; i++)
			{
				this.chblFilter.SetItemChecked(i, true);
			}
		}

		private void btnSelNone_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < this.chblFilter.Items.Count; i++)
			{
				this.chblFilter.SetItemChecked(i, false);
			}
		}

		private void btnSelContrary_Click(object sender, EventArgs e)
		{
			for (int i = 0; i < this.chblFilter.Items.Count; i++)
			{
				bool value = !this.chblFilter.GetItemChecked(i);
				this.chblFilter.SetItemChecked(i, value);
			}
		}

		private bool SelectedStdRoomNode()
		{
			TreeNode selectedNode = this.tvStdRoomFileList.SelectedNode;
			return selectedNode != null && selectedNode.FirstNode == null;
		}

		private int FindSelectedStdRoomIndex()
		{
			if (!this.SelectedStdRoomNode())
			{
				return -1;
			}
			int num = 0;
			int number = this.tvStdRoomFileList.SelectedNode.Index + 1;
			this.GetNodeNumber(this.tvStdRoomFileList.SelectedNode, ref num, ref number);
			return this.m_LeafTreeNodeIndex.FindIndex((int s) => s.CompareTo(number) == 0);
		}

		private void GetLeafNodeInfo(TreeNode tnParent)
		{
			if (tnParent == null)
			{
				return;
			}
			if (tnParent.GetNodeCount(false) != 0)
			{
				tnParent.ImageIndex = 0;
				tnParent.SelectedImageIndex = 0;
				foreach (object obj in tnParent.Nodes)
				{
					TreeNode tnParent2 = (TreeNode)obj;
					this.GetLeafNodeInfo(tnParent2);
				}
				return;
			}
			DbStandardRoom dbStandardRoom = tnParent.Tag as DbStandardRoom;
			if (dbStandardRoom == null)
			{
				tnParent.ImageIndex = 0;
				tnParent.SelectedImageIndex = 0;
				return;
			}
			this.m_DBStdRoomList.Add(dbStandardRoom);
			string name = dbStandardRoom.DbObject.Name;
			Document item = null;
			this.m_DatebaseDocumentList.Add(item);
			this.m_DatebaseDocumentFillNameList.Add(name);
			int num = 0;
			int item2 = tnParent.Index + 1;
			this.GetNodeNumber(tnParent, ref num, ref item2);
			this.m_LeafTreeNodeIndex.Add(item2);
			tnParent.ImageIndex = 1;
			tnParent.SelectedImageIndex = 1;
		}

		private void GetNodeNumber(TreeNode tnCurrentNode, ref int currentLevel, ref int currentNumber)
		{
			if (tnCurrentNode == null)
			{
				return;
			}
			TreeNode parent = tnCurrentNode.Parent;
			if (parent == null)
			{
				return;
			}
			currentLevel++;
			currentNumber += (parent.Index + 1) * (int)Math.Pow(10.0, (double)currentLevel);
			this.GetNodeNumber(parent, ref currentLevel, ref currentNumber);
		}

		private void GetFirstLeafNode(TreeNode tnRootNode, ref TreeNode firstNode)
		{
			if (tnRootNode == null)
			{
				return;
			}
			TreeNode firstNode2 = tnRootNode.FirstNode;
			if (firstNode2 == null)
			{
				firstNode = tnRootNode;
				return;
			}
			this.GetFirstLeafNode(firstNode2, ref firstNode);
		}

		private void btnClearGeneralDocList_Click(object sender, EventArgs e)
		{
			this.m_GeneralDocumentFillNameList.Clear();
			this.m_GeneralDocumentList.Clear();
			this.cmbDocuments.Items.Clear();
			this.cmbDocuments.Items.Add("<Open Document...>");
			Document currentDocument = this.GetCurrentDocument();
			this.Update3DView(currentDocument);
			this.UpdateCheckedTypeList(currentDocument);
		}

		private UIApplication m_UIApplication;

		private bool m_SettingAngle;

		private List<string> m_GeneralDocumentFillNameList = new List<string>();

		private List<Document> m_GeneralDocumentList = new List<Document>();

		private List<DbStandardRoom> m_DBStdRoomList = new List<DbStandardRoom>();

		private List<Document> m_DatebaseDocumentList = new List<Document>();

		private List<string> m_DatebaseDocumentFillNameList = new List<string>();

		private List<int> m_LeafTreeNodeIndex = new List<int>();

		private ElementSelector m_ElementSelector;
	}
}
